/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.slice;

import me.panpf.sketch.Gif;
import me.panpf.sketch.Sketch;
import me.panpf.sketch.SketchImageView;
import me.panpf.sketch.datasource.DataSource;
import me.panpf.sketch.decode.ImageAttrs;
import me.panpf.sketch.decode.NotFoundGifLibraryException;
import me.panpf.sketch.process.GaussianBlurImageProcessor;
import me.panpf.sketch.request.*;
import me.panpf.sketch.sample.AppConfig;
import me.panpf.sketch.sample.ResourceTable;
import me.panpf.sketch.sample.util.DataTransferStation;
import me.panpf.sketch.sample.widget.DialogHolder;
import me.panpf.sketch.uri.AssetUriModel;
import me.panpf.sketch.uri.UriModelManager;
import me.panpf.sketch.util.SketchUtils;
import me.panpf.sketch.util.Utils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.timelinecurves.SpringCurve;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.utils.TextTool;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.ImageSource;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.Size;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static me.panpf.sketch.sample.AppConfig.Key.DISABLE_CORRECT_IMAGE_ORIENTATION;

/**
 * ImageDetailAbility
 */
public class ImageDetailAbility extends Ability implements Component.LongClickedListener, Component.ClickedListener {

    public static final String PARAM_REQUIRED_STRING_DATA_TRANSFER_KEY = "PARAM_REQUIRED_STRING_DATA_TRANSFER_KEY";
    public static final String PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY = "PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY";
    public static final String PARAM_OPTIONAL_INT_DEFAULT_POSITION = "PARAM_OPTIONAL_INT_DEFAULT_POSITION";
    long lastClick = 0;
    boolean scrollToCurrent = false;
    private StackLayout container;
    private PageSlider pageSlider;
    private Text currentItem;
    private Text countItem;
    private DataTransferStation.PageHelper dataTransferHelper;
    private String loadingImageOptionsKey;
    private int position;
    private List<String> imageList;
    private MImageInfo[] infos;
    private boolean isAutoPlay = false;
    private boolean isReverse = false;
    private final EventHandler mainHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            if (isAutoPlay) {
                int pos = pageSlider.getCurrentPage();
                if (pos == pageSlider.getProvider().getCount() - 1) {
                    isReverse = true;
                    pos--;
                } else if (pos == 0) {
                    isReverse = false;
                    pos++;
                } else {
                    if (isReverse) {
                        pos--;
                    } else {
                        pos++;
                    }
                }
                currentItem.setText((pos + 1) + "");
                pageSlider.setCurrentPage(pos, true);
                mainHandler.sendEvent(0, 5000);
            }
            super.processEvent(event);
        }
    };
    private boolean disableCorrectOrientationConfig = false;
    private DialogHolder dialogHolder;
    private GaussianBlurImageProcessor processor;

    /**
     * launch
     *
     * @param ability
     * @param dataTransferKey
     * @param loadingImageOptionsInfo
     * @param defaultPosition
     */
    public static void launch(Ability ability, String dataTransferKey, String loadingImageOptionsInfo, int defaultPosition) {
        Intent intents = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAbilityName(ImageDetailAbility.class.getName())
                .withBundleName(ability.getBundleName())
                .build();
        intents.setOperation(operation);
        IntentParams intentParams = new IntentParams();
        intentParams.setParam(PARAM_REQUIRED_STRING_DATA_TRANSFER_KEY, dataTransferKey);
        intentParams.setParam(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY, loadingImageOptionsInfo);
        intentParams.setParam(PARAM_OPTIONAL_INT_DEFAULT_POSITION, defaultPosition);
        intents.setParams(intentParams);
        ability.startAbility(intents);
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        disableCorrectOrientationConfig = AppConfig.getBoolean(getContext(), DISABLE_CORRECT_IMAGE_ORIENTATION);

        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        ComponentContainer parse = (ComponentContainer) LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_fragment_detail, null, false);
        setUIContent(parse);
        dataTransferHelper = new DataTransferStation.PageHelper(this);
        dataTransferHelper.onCreate(getIntent());
        prepareImageInfos();
        initViews();
        dialogHolder = DialogHolder.getInstance();
    }

    private void prepareImageInfos() {
        TaskDispatcher doWork = getContext().createParallelTaskDispatcher("doWork", TaskPriority.DEFAULT);
        doWork.asyncDispatch(() -> {
            prepareDataList();
            getImageByPosition(position);
            getContext().getUITaskDispatcher().asyncDispatch(this::initPageSlider);
        });
    }

    private void prepareDataList() {
        Intent mIntent = getIntent();
        IntentParams params = mIntent.getParams();
        String dataTransferKey = null;
        if (params != null) {
            dataTransferKey = (String) params.getParam(PARAM_REQUIRED_STRING_DATA_TRANSFER_KEY);
            loadingImageOptionsKey = (String) params.getParam(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY);
            Object param = params.getParam(PARAM_OPTIONAL_INT_DEFAULT_POSITION);
            if (param != null) {
                position = (int) param;
            }
        }
        Object temp = dataTransferHelper.get(dataTransferKey);
        if (temp != null) {
            this.imageList = (List<String>) temp;
        }
        if (this.imageList == null) {
            throw new IllegalArgumentException("Not found image list by dataTransferKey: " + dataTransferKey);
        }
        infos = new MImageInfo[imageList.size()];
    }

    private void initPageSlider() {
        CommonAdapter pagerAdapter = new CommonAdapter(this, infos);
        pageSlider.setProvider(pagerAdapter);
        pageSlider.setPageCacheSize(1);
        currentItem.setText(String.format("%d", position + 1));
        countItem.setText(String.valueOf(infos.length));
        pagerAdapter.setChildLongClickedListener(this);
        pagerAdapter.setClickListener(this);
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
                scrollToCurrent = true;
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }

            @Override
            public void onPageChosen(int i) {
                currentItem.setText((i + 1) + "");
            }
        });
        pageSlider.setCurrentPage(position);
    }

    /**
     * getImageByPosition
     *
     * @param position
     */
    public void getImageByPosition(int position) {
        boolean flag = infos[position] == null || infos[position].imageSource == null;
        if (flag) {
            UriModelManager manager = Sketch.with(getContext()).getConfiguration().getUriModelManager();
            try {
                String path = imageList.get(position);
                if (!TextTool.isNullOrEmpty(path)) {
                    if (manager.match(path).isFromNet()) {
                        Map<String, MImageInfo> datas = NetImageUtils.getInstance().datas;
                        infos[position] = datas.get(path);
                    } else {
                        DataSource dataSource = manager.match(path).getDataSource(getContext(), path, null);
                        initInfo(dataSource, path, position);
                    }
                }
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
        }
    }

    private void initInfo(DataSource dataSource1, String path, int position) {
        try {
            ImageSource imageSource = ImageSource.create(dataSource1.getInputStream(), null);
            ImageInfo imageInfo = imageSource.getImageInfo();
            boolean gifImage = SketchUtils.isGifImage(imageSource);
            infos[position] = new MImageInfo(imageInfo, gifImage, path, imageSource);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void initViews() {
        container = (StackLayout) findComponentById(ResourceTable.Id_container);
        processor = GaussianBlurImageProcessor.makeRadius(30);

        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_pager_detail_content);
        currentItem = (Text) findComponentById(ResourceTable.Id_text_detail_currentItem);
        countItem = (Text) findComponentById(ResourceTable.Id_text_detail_countItem);
    }

    @Override
    public void onLongClicked(Component component) {
        getUITaskDispatcher().asyncDispatch(() -> {
            synchronized (ImageDetailAbility.class) {
                if (component instanceof SketchImageView) {
                    SketchImageView view = (SketchImageView) component;
                    dialogHolder.showInfoDialog(view);
                    dialogHolder.setAutoPlayCallback(() -> {
                        isAutoPlay = !isAutoPlay;
                        mainHandler.sendEvent(0, 5000);
                    });
                }
            }
        });
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        onStop();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mainHandler.removeAllEvent();
        dataTransferHelper.onDestroy();
        pageSlider.release();
    }

    @Override
    public void onClick(Component component) {
        if (System.currentTimeMillis() - lastClick < 1000) {
            return;
        }
        lastClick = System.currentTimeMillis();
        if (isAutoPlay) {
            isAutoPlay = false;
            Utils.toast(this, "Stop auto play");
        } else {
            terminateAbility();
        }
    }

    public static class MImageInfo {
        ImageInfo info;
        boolean isGif;
        String path;
        ImageSource imageSource;

        public MImageInfo(ImageInfo info, boolean isGif, String path, ImageSource imageSource) {
            this.info = info;
            this.isGif = isGif;
            this.path = path;
            this.imageSource = imageSource;
        }
    }

    private class CommonAdapter extends PageSliderProvider {

        private Context context;
        private MImageInfo[] infos;
        private Component.LongClickedListener longClick;
        private Component.ClickedListener clickedListener;

        public CommonAdapter(Context context, MImageInfo[] infos) {
            this.context = context;
            this.infos = infos;
        }

        @Override
        public int getCount() {
            return infos.length;
        }

        public void setChildLongClickedListener(Component.LongClickedListener longClickedListener) {
            this.longClick = longClickedListener;
        }

        private void initErrorPage(ComponentContainer root, int position) {
            Text text = (Text) root.findComponentById(ResourceTable.Id_textHint);
            text.setText("Image display failed");
            Button button = (Button) root.findComponentById(ResourceTable.Id_btnHint);
            button.setText("AGAIN");
            button.setClickedListener(component -> {
                createPageInContainer((ComponentContainer) component.getComponentParent()
                        .getComponentParent().getComponentParent(), position);
            });
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int pos) {
            // 规避PageSlider默认预加载第0， 1， 2页面
            boolean flag1 = pos == 0 || pos == 1 || pos == 2;
            boolean flag2 = position >= 4;
            if (!scrollToCurrent && flag1 && flag2) {
                return new Text(getContext());
            }
            if (!scrollToCurrent && (pos == 0 || pos == 1) && position == 3) {
                return new Text(getContext());
            }
            if (!scrollToCurrent && pos == 0 && position == 2) {
                return new Text(getContext());
            }
            ComponentContainer root = (ComponentContainer) LayoutScatter.getInstance(getContext()).parse(
                    ResourceTable.Layout_error_page, null, false);
            initErrorPage(root, pos);
            ComponentContainer content = (ComponentContainer) root.findComponentById(ResourceTable.Id_content);
            ComponentContainer error = (ComponentContainer) root.findComponentById(ResourceTable.Id_error);
            componentContainer.removeAllComponents();
            getImageByPosition(pos);
            MImageInfo info = infos[pos];
            componentContainer.addComponent(root);
            if (info == null) {
                showHideError(error, true);
                return root;
            }
            SketchImageView bg = new SketchImageView(context);
            setBgImageListener(bg, error);
            SketchImageView image;
            if (info.path.endsWith(".gif")) {
                image = new Gif(context, info.path).setSpeed(3);
            } else {
                if (info.isGif) {
                    image = new Gif(context, info.imageSource).setSpeed(3);
                } else {
                    image = new SketchImageView(context);
                    image.getOptions().setCorrectImageOrientationDisabled(disableCorrectOrientationConfig);
                }
            }
            setImageListener(image, error);
            content.addComponent(bg);
            content.addComponent(image);
            display(error, context, bg, info, true, componentContainer);
            display(error, context, image, info, false, componentContainer);
            return root;
        }

        private void setImageListener(SketchImageView image, ComponentContainer error) {
            image.setClickedListener(component -> {
                if (clickedListener != null) {
                    if (error.getVisibility() == Component.VISIBLE) {
                        return;
                    }
                    clickedListener.onClick(component);
                }
            });
            image.setLongClickListener(component -> {
                if (longClick != null) {
                    longClick.onLongClicked(component);
                }
            });
        }

        private void setBgImageListener(SketchImageView bg, ComponentContainer error) {
            bg.getOptions().setCorrectImageOrientationDisabled(disableCorrectOrientationConfig);
            bg.getOptions().setProcessor(processor);
            bg.setClickedListener(component -> {
                if (clickedListener != null) {
                    if (error.getVisibility() == Component.VISIBLE) {
                        return;
                    }
                    clickedListener.onClick(component);
                }
            });
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i1, Object o1) {
            if (o1 instanceof Component) {
                componentContainer.removeComponent((Component) o1);
            }
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o1) {
            return o1 == component;
        }

        @Override
        public String getPageTitle(int position) {
            return "title";
        }

        private void display(ComponentContainer error, Context context, SketchImageView image, MImageInfo info, boolean isbg, ComponentContainer componentContainer) {
            context.getUITaskDispatcher().asyncDispatch(() -> {
                String path = info.path;
                image.setShowImageFromEnabled(AppConfig.getBoolean(getContext(), AppConfig.Key.SHOW_IMAGE_FROM_FLAG));
                image.setShowDownloadProgressEnabled(AppConfig.getBoolean(getContext(), AppConfig.Key.SHOW_IMAGE_DOWNLOAD_PROGRESS));
                image.setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onUpdateDownloadProgress(int totalLength, int completedLength) {
                        showProgressDialog(totalLength, completedLength, error);
                        error.setVisibility(Component.HIDE);
                    }
                });
                image.setDisplayListener(new DisplayListener() {
                    @Override
                    public void onStarted() {
                    }

                    @Override
                    public void onCompleted(Element drawable, ImageFrom imageFrom, ImageAttrs imageAttrs) {
                        showProgressHideWithAnimation(false, error);
                    }

                    @Override
                    public void onError(ErrorCause cause) {
                        showProgressHideWithAnimation(true, error);
                    }

                    @Override
                    public void onCanceled(CancelCause cause) {
                        if (image instanceof Gif) {
                            return;
                        }
                        if (AppConfig.getBoolean(context, AppConfig.Key.MOBILE_NETWORK_PAUSE_DOWNLOAD)) {
                            if (error != null) {
                                showProgressHideWithAnimation(true, error);
                                Text text = (Text) error.findComponentById(ResourceTable.Id_textHint);
                                text.setText("Pause to download new image for saving traffic");
                                Button button = (Button) error.findComponentById(ResourceTable.Id_btnHint);
                                button.setText("I DO NOT CARE");
                            }
                        }
                    }
                });
                setImageAction(image, path, isbg, info, componentContainer);
            });
        }

        /**
         * setImageAction
         *
         * @param image
         * @param path
         * @param isBig
         * @param info
         * @param componentContainer
         */
        private void setImageAction(SketchImageView image, String path, boolean isBig, MImageInfo info, ComponentContainer componentContainer) {
            image.setZoomEnabled(true);
            image.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            if (path.startsWith(AssetUriModel.SCHEME)) {
                Sketch.with(context).displayFromAsset(path, image).commit();
            } else {
                Sketch.with(context).display(path, image).commit();
            }
            if (isBig) {
                changeSizeBG(image, info.info.size);
            } else {
                changeSize(image, info.info.size, componentContainer);
            }
        }

        /**
         * showProgressDialog
         *
         * @param totalLength
         * @param completedLength
         * @param error
         */
        private void showProgressDialog(int totalLength, int completedLength, ComponentContainer error) {
            ComponentContainer parent = (ComponentContainer) error.getComponentParent();
            RoundProgressBar roundProgress = (RoundProgressBar) parent.findComponentById(ResourceTable.Id_roundProgress);
            roundProgress.setProgressHintTextSize(20);
            roundProgress.setMaxValue(Math.abs(totalLength));
            int value = (100 * Math.abs(completedLength)) / Math.abs(totalLength);
            if (value > 99) {
                roundProgress.setVisibility(Component.HIDE);
                roundProgress.setProgressValue(Math.abs(totalLength));
                roundProgress.setProgressHintText("100%");
            } else {
                if (roundProgress.getVisibility() == Component.HIDE) roundProgress.setVisibility(Component.VISIBLE);
                roundProgress.setProgressValue(Math.abs(completedLength));
                roundProgress.setProgressHintText(value + "%");
            }
        }

        /**
         * showProgressHideWithAnimation
         *
         * @param isWithAnimation
         * @param error
         */
        private void showProgressHideWithAnimation(boolean isWithAnimation, ComponentContainer error) {
            if (error != null) {
                ComponentContainer parent = (ComponentContainer) error.getComponentParent();
                RoundProgressBar roundProgress = (RoundProgressBar) parent.findComponentById(ResourceTable.Id_roundProgress);
                roundProgress.setVisibility(Component.HIDE);
                showHideError(error, isWithAnimation);
            }
        }

        private void showHideError(ComponentContainer error, boolean isDoShow) {
            if (error == null) {
                return;
            }

            if (isDoShow) {
                error.setVisibility(Component.VISIBLE);
                Component errorLayout = error.findComponentById(ResourceTable.Id_errorLayout);
                {
                    AnimatorProperty animatorProperty = new AnimatorProperty(errorLayout);
                    animatorProperty.alphaFrom(0);
                    animatorProperty.setCurve(new SpringCurve(0.1f, 10f));
                    animatorProperty.moveFromY(200);
                    animatorProperty.moveToY(0);
                    animatorProperty.setDuration(1200);
                    animatorProperty.start();
                }
            } else {
                error.setVisibility(Component.INVISIBLE);
            }
        }

        private void changeSize(SketchImageView image, Size size, ComponentContainer container) {
            image.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            int ratioW = container.getWidth() * 1000 / size.width;
            int ratioH = container.getHeight() * 1000 / size.height;

            int min = Math.min(ratioW, ratioH);

            int usedWidth = size.width * min / 1000;
            int usedHeight = size.height * min / 1000;

            int lr = container.getWidth() - usedWidth;
            int tb = container.getHeight() - usedHeight;

            image.setMarginLeft(lr / 2);
            image.setMarginTop(tb / 2);

            image.setWidth(usedWidth);
            image.setHeight(usedHeight);
        }

        private void changeSizeBG(SketchImageView image, Size originSize) {
            int ratioW = container.getWidth() * 1000 / originSize.width;
            int ratioH = container.getHeight() * 1000 / originSize.height;

            int max = Math.max(ratioW, ratioH);

            int usedWidth = originSize.width * max / 1000;
            int usedHeight = originSize.height * max / 1000;

            int lr = container.getWidth() - usedWidth;
            int tb = container.getHeight() - usedHeight;

            image.setMarginLeft(lr / 2);
            image.setMarginTop(tb / 2);

            image.setWidth(usedWidth);
            image.setHeight(usedHeight);
        }

        /**
         * setClickListener
         *
         * @param clickListener
         */
        public void setClickListener(Component.ClickedListener clickListener) {
            this.clickedListener = clickListener;
        }
    }
}
